import datetime
import wsgiref.handlers
import statsdb
import statsdt

from google.appengine.ext import webapp
from google.appengine.ext import db
import gviz_api

class QueryStats(webapp.RequestHandler):
  def get(self):
    tags = self.request.get("tags").split(" ")
    if 0 == len(self.request.get("begin")):
      begin = datetime.datetime.strptime("197001010000", "%Y%m%d%H%M%S")
    else:
      begin = datetime.datetime.strptime(self.request.get("begin"), "%Y%m%d%H%M%S")
    if 0 == len(self.request.get("end")):
      end = datetime.datetime.strptime("207001010000", "%Y%m%d%H%M%S")
    else:
      end = datetime.datetime.strptime(self.request.get("end"), "%Y%m%d%H%M%S")
    #Get request tqx for response
    tqx = self.request.get("tqx")
    reqId = 0
    if tqx:
      params = dict([p.split(":") for p in tqx.split(";")])
      reqId = params["reqId"]

      
    records = statsdb.QueryRecordsByTag(begin, end, tags)
    if 0 == len(records):
      self.response.out.write("google.visualization.Query.setResponse(\
        {version:'0.5',reqId:'"+str(reqId)+"',status:'error',errors:\
        [{reason:'invalid_query',message:'Invalid query',\
        detailed_message:'No data found for "+" ".join(tags)+".'}]});")
      return  
                
    datefmt = str(self.request.get("dfmt"))
    x = self.request.get("x").split(" ")
    y = self.request.get("y").split(" ")
        
    self.response.headers["Content-Type"] = "text/plain"   
    dtStats = self.getDTStats(records, x, y)
    cols, rows, colOrder = dtStats.fill(records, tags, datefmt, x, y)

    data_table = gviz_api.DataTable(cols)
    data_table.AppendData(rows)
    self.response.out.write(data_table.ToJSonResponse(
          columns_order = colOrder,
          order_by = colOrder[0],
          req_id = reqId))
  
  def getDTStats(self, results, x, y):
    if 0 == len("".join(x)) \
    and 0 == len("".join(y)):
      return statsdt.DTX()
    if "date" in x:
      return statsdt.DTX()
    if "date" in y:
      return statsdt.DTY()
    if not "date" in x \
    and not "date" in y:
      return statsdt.DTTags()
    # More conditions later    
    return statsdt.BaseStatsDT() #default
  
class QueryTags(webapp.RequestHandler):
  def get(self):
    #Get request tqx for response
    tqx = self.request.get("tqx")
    reqId = 0
    if tqx:
      params = dict([p.split(":") for p in tqx.split(";")])
      reqId = params["reqId"]
    
    self.response.headers["Content-Type"] = "text/plain"
    direction = self.request.get("direction")
    if "next" == direction:
      bookmark = statsdb.GetTag(self.request.get("tag"))[1]
    elif "related" == direction:
      bookmark = self.request.get("tag")
    pagesize = 10
    if True == self.request.get("pagesize").isdigit():
      pagesize = int(self.request.get("pagesize"));
    tags, bookmark = statsdb.GetTags(bookmark, direction, pagesize)
    
    cols = [("name", "string"),("refCount", "number"),("bookmark", "string")]
    if "next" == direction:
      rows = [[tag.name, len(tag.records), ""] for tag in tags]
    elif "related" == direction:
      rows = [[tag, 0, ""] for tag in tags]
    if len(rows)>0:
      if "next" == direction \
      and len(rows) == pagesize:
        rows[-1][2] = "bookmark"
    colOrder = ["name", "refCount", "bookmark"]
    
    data_table = gviz_api.DataTable(cols)
    data_table.AppendData(rows)
    self.response.out.write(data_table.ToJSonResponse(
          columns_order = colOrder,
          req_id = reqId))

class QueryHistory(webapp.RequestHandler):
  def get(self):
    #Get request tqx for response
    tqx = self.request.get("tqx")
    reqId = 0
    if tqx:
      params = dict([p.split(":") for p in tqx.split(";")])
      reqId = params["reqId"]
    found = True
    if "false" == self.request.get("found"):
      found = False
    
    self.response.headers["Content-Type"] = "text/plain"
    results = statsdb.History.gql("WHERE found = :1 ORDER BY qcount ASC", found)
    results.fetch(20)
    
    cols = [("tags", "string"),("qcount", "number")]
    rows = [["".join(history.tags), history.qcount] for history in results]
    colOrder = ["tags", "qcount"] 
    
    data_table = gviz_api.DataTable(cols)
    data_table.AppendData(rows)
    self.response.out.write(data_table.ToJSonResponse(
          columns_order = colOrder,
          order_by = colOrder[0],
          req_id = reqId))


def main():
  application = webapp.WSGIApplication([("/querystats", QueryStats),
                                        ("/querytags", QueryTags),
                                        ("/queryhistory", QueryHistory)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
